/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.sd.chat;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;

/**
 *
 * @author Old
 */
public class TCPConReceiver extends Thread {

    private ServerManager myManager;
    private boolean shutdown = false;
    private Logger log = new Logger(true);

    public TCPConReceiver(ServerManager myMan) {
        this.myManager = myMan;
    }

    public void run() {

        try {
            int serverPort = 7676;
            log.outln("A Escuta no Porto 7676");
            ServerSocket listenSocket = new ServerSocket(serverPort);
            log.outln("LISTEN SOCKET=" + listenSocket);
            while (!isShutdown()) {
                UUID uniqueKey = UUID.randomUUID();
                Socket clientSocket = listenSocket.accept(); // BLOQUEANTE
                log.outln("CLIENT_SOCKET (created at accept())=" + clientSocket);

                this.myManager.newConnection(uniqueKey, new ClientHandler(clientSocket, uniqueKey, this.myManager));
                log.outln("connection added to manager");
            }
        } catch (IOException e) {
            System.out.println("Listen:" + e.getMessage());
        }
    }
    
    
    public synchronized void shutdown(){
        this.setShutdown(true);
    }

    public boolean isShutdown() {
        return shutdown;
    }

    public void setShutdown(boolean shutdown) {
        this.shutdown = shutdown;
    }
}
